package com.shivandragon.controller;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.shivandragon.utils.MongoSingletonHolder;

public class ImgController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9039761350981585006L;
	
	private MongoSingletonHolder mongoSingletonHolder = MongoSingletonHolder.getInstance();

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String _id = request.getParameter("_id");
		int slideIndex = Integer.parseInt(request.getParameter("slideIndex"));
		DBCollection dbCollection = mongoSingletonHolder.getPresentationsDBCollection();
		DBObject prez = dbCollection.findOne(new BasicDBObject("_id", new ObjectId(_id)), new BasicDBObject("img"+slideIndex, 1));
		if(prez!=null) {
			byte[] imgData = (byte[]) prez.get("img"+slideIndex);
			writeImageToResponse(imgData, response);		
		} else {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
		}
	}
	
	private void writeImageToResponse(byte[] image, HttpServletResponse response) throws IOException {
		response.setContentType("image/jpeg");
		OutputStream out = response.getOutputStream();
		out.write(image);
		out.flush();
		out.close();
	}
}
